// Source :
// Author : simba
// Date   : 2016-06-08
//常用位操作技巧

package main

import (
	"fmt"
)

// 获取0-n之间的所有偶数
func even(a int) []int {
	var array []int

	for i := 0; i < a; i++ {
		if i&0x1 == 0 {
			array = append(array, i)
		}
	}
	return array
}

// 互换两个变量的值
// 不需要使用第三个变量做中间变量
func swap(a, b int) (int, int) {
	a ^= b // 异或等于运算
	b ^= a
	a ^= b
	return a, b
}

// 左移、右移运算
func shifting(a int) int {
	a = a << 1
	a = a >> 1
	return a
}

// 变换符号
func nagation(a int) int {
	return ^a + 1
}

//求绝对值
func CalcAbs(a int) int {
	return (a ^ a>>31) - a>>31
}

//二进制逆序
func ByteReverse(a int) int {
	a = ((a & 0xAAAA) >> 1) | ((a & 0x5555) << 1)
	a = ((a & 0xCCCC) >> 2) | ((a & 0x3333) << 2)
	a = ((a & 0xF0F0) >> 4) | ((a & 0x0F0F) << 4)
	a = ((a & 0xFF00) >> 8) | ((a & 0x00FF) << 8)
	return a
}

//求1的个数
func CalcOneNum(a int) int {
	a = ((a & 0xAAAA) >> 1) + (a & 0x5555)
	a = ((a & 0xCCCC) >> 2) + (a & 0x3333)
	a = ((a & 0xF0F0) >> 4) + (a & 0x0F0F)
	a = ((a & 0xFF00) >> 8) + (a & 0x00FF)
	return a
}

func main() {
	fmt.Printf("偶数: %v\n", even(100))
	a, b := swap(100, 200)
	fmt.Printf("交换: %d\t%d\n", a, b)
	fmt.Printf("位移: %d\n", shifting(100))
	fmt.Printf("变换符号: %d\n", nagation(100))
	fmt.Printf("绝对值: %d\n", CalcAbs(-100))
	fmt.Printf("逆序值: %d\n", ByteReverse(100))
	fmt.Printf("1的个数: %d\n", CalcOneNum(100))
}
